import {
  loginREQ,
  loginOutREQ
} from '@/api/user'
import { setToken, getToken } from '@/libs/util'
import router from '@/router'
import config from '@/config'

export default {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        loginREQ({
          userName,
          password
        }).then(res => {
          commit('setToken', res)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    handleLogOut ({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        loginOutREQ()
          .then(() => {
            commit('setToken', '')
            router.push({
              path: config.loginName
            })
            resolve()
          })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    }
  }
}
